<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>Java中的异常处理 | 奉孝的测开日记</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
  
  
    <link rel="alternate" href="/blog/atom.xml" title="奉孝的测开日记" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/blog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/blog/css/style.css">

  
    
<link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.min.css">

  
  
    
<link rel="stylesheet" href="/blog/localshare/css/share.css">

  
  
  
<meta name="generator" content="Hexo 5.4.2"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/blog/" id="logo">奉孝的测开日记</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/blog/" id="subtitle">开启自我改变的原动力</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        
          <a class="main-nav-link" href="/blog/."><i class="fa fa-home"></i> 首页</a>
        
          <a class="main-nav-link" href="/blog/archives/"><i class="fa fa-archive"></i> 归档</a>
        
          <a class="main-nav-link" href="/blog/about/"><i class="fa fa-user"></i> 关于</a>
        
      </nav>
    </div>
    <div id="search-form">
      <div id="result-mask" class="hide"></div>
      <label><input id="search-key" type="text" autocomplete="off" placeholder="搜索"></label>
      <div id="result-wrap" class="hide">
        <div id="search-result"></div>
      </div>
      <div class="hide">
        <template id="search-tpl">
          <div class="item">
            <a href="/{path}" title="{title}">
              <div class="title">{title}</div>
              <div class="time">{date}</div>
              <div class="tags">{tags}</div>
            </a>
          </div>
        </template>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-Java中的异常处理" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      Java中的异常处理
    </h1>
  


      </header>
    
    <div class="article-meta">
      
      <span class="article-date">
  <i class="fa fa-date"></i>
  <time class="dt-published" datetime="2022-08-19T07:01:11.000Z" itemprop="datePublished">2022年08月19日</time>
</span>
      
  <div class="article-category">
    <i class="fa fa-classify"></i>
    <a class="article-category-link" href="/blog/categories/Java/">Java</a>
  </div>

      
        <span class="article-views">
  <i class="fa fa-views"></i>
  <i id="busuanzi_container_page_pv">
      <i id="busuanzi_value_page_pv"></i>
  </i>
</span>

      
      
<a href="/blog/2022/08/19/Java%E4%B8%AD%E7%9A%84%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/#comments" class="article-comment-link">
  
    
    
    
    
    
  
  <i class="fa fa-commt"></i>
  留言
</a>


    </div>
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h1 id="一、异常和-try-catch"><a href="#一、异常和-try-catch" class="headerlink" title="一、异常和 try catch"></a>一、异常和 try catch</h1><h2 id="1-1-初识异常"><a href="#1-1-初识异常" class="headerlink" title="1.1 初识异常"></a>1.1 初识异常</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">class Demo&#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        // &gt;&gt; TODO try 语句中如果发生了异常（Exception），那么程序会跳转到catch语句。</span><br><span class="line">        // &gt;&gt; TODO Java会将异常相关信息封装在一个异常类的实例中，ex是指向这个异常实例的引用</span><br><span class="line">        // &gt;&gt; TODO &quot;处理&quot;最简单的方法，就是调用printStackTrace将异常信息输出到控制台</span><br><span class="line">        // &gt;&gt; TODO catch语句执行完毕，程序会继续向下顺序执行</span><br><span class="line">        try &#123;</span><br><span class="line">            int[] arr = new int[1];</span><br><span class="line">            arr[1] = 9;</span><br><span class="line">        &#125; catch (Exception ex) &#123;</span><br><span class="line">            ex.printStackTrace(); // java.lang.ArrayIndexOutOfBoundsException: 1</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;</span><br><span class="line">            String str = &quot;&quot;;</span><br><span class="line">            str.substring(9, 10);</span><br><span class="line">        &#125; catch (Exception ex) &#123;</span><br><span class="line">            ex.printStackTrace(); // java.lang.StringIndexOutOfBoundsException: String index out of range: 10</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;程序执行结束&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-2-异常的分类"><a href="#1-2-异常的分类" class="headerlink" title="1.2 异常的分类"></a>1.2 异常的分类</h2><h3 id="1-2-1-按照异常的继承关系分类"><a href="#1-2-1-按照异常的继承关系分类" class="headerlink" title="1.2.1 按照异常的继承关系分类"></a>1.2.1 按照异常的继承关系分类</h3><ul>
<li>异常也是 Java 中的类</li>
<li>所有异常的父类：Throwable</li>
<li>两类异常：Error 和 Exception  <img src="/blog/2022/08/19/Java%E4%B8%AD%E7%9A%84%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/Throwable.png" class="" title="Throwable">  </li>
<li><em>idea小技巧</em>*<br>按两下Shift，输入Throwable，找到该类文件，然后菜单栏Navigate-&gt;Type Hierarchy<h3 id="1-2-2-按照处理方式不同分类"><a href="#1-2-2-按照处理方式不同分类" class="headerlink" title="1.2.2 按照处理方式不同分类"></a>1.2.2 按照处理方式不同分类</h3></li>
<li>checked exception：语法要求必须要用 try catch 或者 throws 语句处理的异常</li>
<li>unchecked exception：语法不要求一定要用 try catch 或者 throws 语句处理的异常</li>
<li>Error 和 RuntimeException 是 unchecked exception的父类。我们一般使用 RuntimeException<br>怎么理解RuntimeException 是 unchecked exception的父类？<br><code>int num = 5/0; // 会报ArithmeticException，而ArithmeticException继承RuntimeException，此异常不强制处理</code>  <h3 id="1-2-3-小题目"><a href="#1-2-3-小题目" class="headerlink" title="1.2.3 小题目"></a>1.2.3 小题目</h3>NoClassDefFoundError 和 ClassNotFoundException 有什么区别？<br>直观区别：一个是异常，一个是错误  </li>
</ul>
<ol>
<li>ClassNotFoundException和NoClassDefFoundError都发生在JVM在classpath下找不到所需的类时</li>
<li>ClassNotFoundException<br>当应用尝试在类路径中用全限量名去加载某个类时，如果找你不到它的定义就会报CLassNotFoundException。它是一个可检测异常.使用反射时，要注意这个异常。    <figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">class Demo&#123;</span><br><span class="line">    public static void main(String[] args) throws ClassNotFoundException &#123;</span><br><span class="line">        Class.forName(&quot;com.test.api&quot;); // 此类不存在，就会报ClassNotFoundException</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">```  </span><br><span class="line">3. NoClassDefFoundError  </span><br><span class="line">NoClassDefFoundError是一种致命错误。  </span><br><span class="line">当JVM尝试通过new关键字创建一个类实例或者方法调用来加载一个类时找不到这个类的定义就会出现这个错误。  </span><br><span class="line">通常是编译时正常编译，但是运行时找不到这个类.  </span><br><span class="line">通常发生在执行动态代码块或者初始化静态字段时报了异常，从而导致类初始化失败而引发NoClassDefFoundError  </span><br><span class="line">**如下代码就是在初始化静态字段时报了异常**    </span><br><span class="line">```shell</span><br><span class="line">public class ClassWithInitErrors &#123;</span><br><span class="line">    static int data = 1 / 0;</span><br><span class="line">&#125;</span><br><span class="line">public class NoClassDefFoundErrorDemo &#123;</span><br><span class="line">    public ClassWithInitErrors getClassWithInitErrors() &#123;</span><br><span class="line">        ClassWithInitErrors test;</span><br><span class="line">        try &#123;</span><br><span class="line">            test = new ClassWithInitErrors();</span><br><span class="line">        &#125; catch (Throwable t) &#123;</span><br><span class="line">            System.out.println(t);</span><br><span class="line">        &#125;</span><br><span class="line">        test = new ClassWithInitErrors();</span><br><span class="line">        return test;</span><br><span class="line">    &#125;</span><br><span class="line">    public static void main(String[] args)&#123;</span><br><span class="line">        NoClassDefFoundErrorDemo noClassDefFoundErrorDemo = new NoClassDefFoundErrorDemo();</span><br><span class="line">        noClassDefFoundErrorDemo.getClassWithInitErrors();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">```  </span><br><span class="line">4. 总结  </span><br><span class="line">ClassNotFoundException与NoClassDefException核心区别是，前者强调运行时无法匹配到指定参数名称的类，后者强调编译时没问题，运行时却无法实例化一个类。</span><br><span class="line">最常见的解决方法是检查是否依赖了相关包或者相关包是否有冲突。  </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 1.3 异常使用基本原则</span></span></span><br><span class="line">1. 尽量不要捕获类似 Exception 这样的通用异常，而是应该捕获特定异常</span><br><span class="line">2. 不要生吞（swallow）异常。</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 1.4 异常的传递</span></span></span><br><span class="line">* Java 异常的的归宿：要么沿着方法调栈顺序一路抛，最终造成当前线</span><br><span class="line">程出错退出，要么被 catch 住</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 1.5 自定义异常</span></span></span><br><span class="line">* 异常最重要的信息：类型，错误信息和出错时的调用栈</span><br><span class="line">```shell</span><br><span class="line">public class MyException extends Exception&#123;</span><br><span class="line">    public MyException()&#123;</span><br><span class="line">    &#125;</span><br><span class="line">    public MyException(String message)&#123;</span><br><span class="line">        super(message);</span><br><span class="line">    &#125;</span><br><span class="line">    public MyException(String message, Throwable cause)&#123;</span><br><span class="line">        super(message, cause);</span><br><span class="line">    &#125;</span><br><span class="line">    public MyException(Throwable cause)&#123;</span><br><span class="line">        super(cause);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="1-6-try-catch-finally-语句"><a href="#1-6-try-catch-finally-语句" class="headerlink" title="1.6 try catch finally 语句"></a>1.6 try catch finally 语句</h2><h3 id="1-6-1-catch-多种异常"><a href="#1-6-1-catch-多种异常" class="headerlink" title="1.6.1 catch 多种异常"></a>1.6.1 catch 多种异常</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">try &#123;</span><br><span class="line">    ...;</span><br><span class="line">    // &gt;&gt; TODO 如果一个方法抛出多种异常，可以针对多个类型有多种catch语语句</span><br><span class="line">&#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125; catch (IOException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br><span class="line">```  </span><br><span class="line">```shell</span><br><span class="line">try &#123;</span><br><span class="line">    ...;</span><br><span class="line">    // &gt;&gt; TODO 如果捕获了不同类型的异常，但是处理方式一样，可以用简化模式</span><br><span class="line">&#125; catch (ClassNotFoundException | IOException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-6-2-try-finally"><a href="#1-6-2-try-finally" class="headerlink" title="1.6.2 try finally"></a>1.6.2 try finally</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"> public static void main(String[] args) &#123;</span><br><span class="line">        System.out.println(withFinally());</span><br><span class="line">        System.out.println(VAL);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">private static int withFinally() &#123;</span><br><span class="line">    int len = 0;</span><br><span class="line">    try &#123;</span><br><span class="line">//            String s = null; </span><br><span class="line">        String s = &quot;abc&quot;;</span><br><span class="line">        return s.length();</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        // &gt;&gt; TODO 可以认为finally语句会在方法返回后，后面的方法开始前，会在return语句后</span><br><span class="line">        // &gt;&gt; TODO 无论是因为return结束还是因为异常结束，finally语句都会执行</span><br><span class="line">        System.out.println(&quot;执行finally语句&quot;);</span><br><span class="line">           &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-6-3-try-catch-finally"><a href="#1-6-3-try-catch-finally" class="headerlink" title="1.6.3 try catch finally"></a>1.6.3 try catch finally</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">private static int VAL = 0;</span><br><span class="line"></span><br><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">    System.out.println(withFinally());</span><br><span class="line">    System.out.println(VAL);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">private static int withFinally() &#123;</span><br><span class="line">    int len = 0;</span><br><span class="line">    try &#123;</span><br><span class="line">        String s = null;</span><br><span class="line">//            String s = &quot;abc&quot;;</span><br><span class="line">        return s.length();</span><br><span class="line">    &#125; catch (Exception ex) &#123;</span><br><span class="line">        // &gt;&gt; TODO 异常的处理：在有返回值的情况下，返回一个特殊的值，代表情况不对，有异常</span><br><span class="line">        len = -1;</span><br><span class="line">        System.out.println(&quot;执行catch里的return语句&quot;);</span><br><span class="line">        return len;</span><br><span class="line">    &#125; finally &#123;</span><br><span class="line">        // &gt;&gt; TODO 可以认为finally语句会在方法返回后，后面的方法开始前，会在return语句后</span><br><span class="line">        // &gt;&gt; TODO 无论是因为return结束还是因为异常结束，finally语句都会执行</span><br><span class="line">        System.out.println(&quot;执行finally语句&quot;);</span><br><span class="line">        // &gt;&gt; TODO finally里最好不要有return语句,会打乱exception的传递</span><br><span class="line">//            return -2;</span><br><span class="line"></span><br><span class="line">        // &gt;&gt; TODO finally里给return用的变量值赋值没用</span><br><span class="line">//            len = -2;</span><br><span class="line"></span><br><span class="line">        VAL = 999;</span><br><span class="line">        System.out.println(&quot;finally语句执行完毕&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-6-4-自动回收资源的-try-语句-try-with-resource"><a href="#1-6-4-自动回收资源的-try-语句-try-with-resource" class="headerlink" title="1.6.4 自动回收资源的 try 语句(try-with-resource)"></a>1.6.4 自动回收资源的 try 语句(try-with-resource)</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">public class MyAutoClosableResource implements AutoCloseable &#123;</span><br><span class="line">    private String resName;</span><br><span class="line">    private int counter;</span><br><span class="line">    public MyAutoClosableResource(String resName) &#123;</span><br><span class="line">        this.resName = resName;</span><br><span class="line">    &#125;</span><br><span class="line">    public String read() throws IOException &#123;</span><br><span class="line">        counter++;</span><br><span class="line">        if (Math.random() &gt; 0.1) &#123;</span><br><span class="line">            return &quot;You got lucky to read from &quot; + resName + &quot; for &quot; + counter + &quot; times...&quot;;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            throw new IOException(&quot;resource不存在哦&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    public void close() throws Exception &#123;</span><br><span class="line">        System.out.println(&quot;资源释放了:&quot; + resName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">public class TryWithResource &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        try (</span><br><span class="line">             MyAutoClosableResource res1 = new MyAutoClosableResource(&quot;res1&quot;);</span><br><span class="line">             MyAutoClosableResource res2 = new MyAutoClosableResource(&quot;res2&quot;)</span><br><span class="line">        ) &#123;</span><br><span class="line">            while (true) &#123;</span><br><span class="line">                System.out.println(res1.read());</span><br><span class="line">                System.out.println(res2.read());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">```    </span><br><span class="line">以上代码运行结果  </span><br><span class="line">&#123;% asset_img TryWithResource.png TryWithResource %&#125;  </span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="comment"># 1.7 Java 中的常见异常</span></span></span><br><span class="line">* NullPointerException</span><br><span class="line">* IndexOutOfBoundsException</span><br><span class="line">* ClassCastException</span><br><span class="line">```shell</span><br><span class="line">class Animal&#123;</span><br><span class="line">    public void run()&#123;</span><br><span class="line">        System.out.println(&quot;动物跑&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Dog extends Animal&#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        System.out.println(&quot;狗跑&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args)&#123;</span><br><span class="line">        Animal animal = new Animal();</span><br><span class="line">        Dog dog = (Dog) animal; // 父类引用指向的对象的类型不是子类的时候强制转换将产生java.lang.ClassCastException异常</span><br><span class="line">        dog.run();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<ul>
<li>ClassNotFoundException</li>
<li>IOException</li>
</ul>

        
            <div id="toc-article">
                
  <div class="widget-wrap" id="toc-wrap">
    <h3 class="widget-title"><i class="fa fa-toc"></i> 文章目录</h3>
    <div class="widget">
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%BC%82%E5%B8%B8%E5%92%8C-try-catch"><span class="toc-text">一、异常和 try catch</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-%E5%88%9D%E8%AF%86%E5%BC%82%E5%B8%B8"><span class="toc-text">1.1 初识异常</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-%E5%BC%82%E5%B8%B8%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">1.2 异常的分类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-1-%E6%8C%89%E7%85%A7%E5%BC%82%E5%B8%B8%E7%9A%84%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB%E5%88%86%E7%B1%BB"><span class="toc-text">1.2.1 按照异常的继承关系分类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-2-%E6%8C%89%E7%85%A7%E5%A4%84%E7%90%86%E6%96%B9%E5%BC%8F%E4%B8%8D%E5%90%8C%E5%88%86%E7%B1%BB"><span class="toc-text">1.2.2 按照处理方式不同分类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-3-%E5%B0%8F%E9%A2%98%E7%9B%AE"><span class="toc-text">1.2.3 小题目</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-6-try-catch-finally-%E8%AF%AD%E5%8F%A5"><span class="toc-text">1.6 try catch finally 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-1-catch-%E5%A4%9A%E7%A7%8D%E5%BC%82%E5%B8%B8"><span class="toc-text">1.6.1 catch 多种异常</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-2-try-finally"><span class="toc-text">1.6.2 try finally</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-3-try-catch-finally"><span class="toc-text">1.6.3 try catch finally</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-6-4-%E8%87%AA%E5%8A%A8%E5%9B%9E%E6%94%B6%E8%B5%84%E6%BA%90%E7%9A%84-try-%E8%AF%AD%E5%8F%A5-try-with-resource"><span class="toc-text">1.6.4 自动回收资源的 try 语句(try-with-resource)</span></a></li></ol></li></ol></li></ol>
    </div>
  </div>


            </div>
        
        
          <blockquote id="copyright">
              <p>原文链接: <a href="http://haohongbin.gitee.io/blog/2022/08/19/Java中的异常处理/">http://haohongbin.gitee.io/blog/2022/08/19/Java中的异常处理/</a></p>
              <p>版权声明: 转载请注明出处.</p>
          </blockquote>
        
      
    </div>
    <footer class="article-footer">
      
        <div class="article-tag-wrap">
          

          
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/%E5%AD%A6%E4%B9%A0%E6%80%BB%E7%BB%93/" rel="tag">学习总结</a></li></ul>

          
    <div class="social-share">
      <span>分享到:</span>
    </div>



        </div>
      
      
        
<nav id="article-nav">
  
    <a href="/blog/2022/07/19/SpringBoot%E5%85%A5%E9%97%A8/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">older</strong>
      <div class="article-nav-title">
        
          Boot入门
        
      </div>
    </a>
  
  
    <a href="/blog/2022/09/05/String%E3%80%81StringBuffer%E3%80%81StringBuilder%E5%8C%BA%E5%88%AB/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">newer</strong>
      <div class="article-nav-title">
        
          String、StringBuffer、StringBuilder区别
        
      </div>
    </a>
  
</nav>

      
      
        








      
    </footer>
  </div>
</article>
</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title"><i class="fa fa-posts"></i> 最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/blog/2023/03/14/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E5%88%97%E8%A1%A8%E5%92%8C%E5%85%83%E7%BB%84/">(no title)</a>
          </li>
        
          <li>
            <a href="/blog/2023/03/09/Java%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95Mock%E7%A5%9E%E5%99%A8/">Java单元测试Mock神器</a>
          </li>
        
          <li>
            <a href="/blog/2023/02/21/Pytest%E6%89%A7%E8%A1%8C%E7%94%A8%E4%BE%8B%E7%9A%84%E5%A4%9A%E7%A7%8D%E6%96%B9%E5%BC%8F/">Pytest执行用例的多种方式</a>
          </li>
        
          <li>
            <a href="/blog/2023/02/20/SQL%E6%9F%A5%E8%AF%A2%E5%9C%BA%E6%99%AF/">SQL查询场景</a>
          </li>
        
          <li>
            <a href="/blog/2023/01/18/MySQL%E5%91%BD%E4%BB%A4%E6%89%8B%E5%86%8C/">MySQL命令手册</a>
          </li>
        
      </ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title"><i class="fa fa-tag"></i> 标签云</h3>
    <div class="widget tagcloud">
      <a href="/blog/tags/MySQL/" style="font-size: 15px;">MySQL</a> <a href="/blog/tags/%E5%88%86%E4%BA%AB/" style="font-size: 15px;">分享</a> <a href="/blog/tags/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/" style="font-size: 10px;">单元测试</a> <a href="/blog/tags/%E5%AD%A6%E4%B9%A0%E6%80%BB%E7%BB%93/" style="font-size: 20px;">学习总结</a> <a href="/blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96/" style="font-size: 10px;">自动化</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title"><i class="fa fa-classify"></i> 分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Java/">Java</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Java%E6%A0%B8%E5%BF%83%E6%8A%80%E6%9C%AF/">Java核心技术</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/hexo%E5%8D%9A%E5%AE%A2/">hexo博客</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/vim/">vim</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E5%90%8E%E7%AB%AF/">后端</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E6%B5%8B%E8%AF%95/">测试</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E6%B5%8B%E8%AF%95%E8%BF%9B%E9%98%B6/">测试进阶</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title"><i class="fa fa-archive"></i> 归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2023/">2023年</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/">2022年</a><span class="archive-list-count">10</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title"><i class="fa fa-tag"></i> 标签</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/MySQL/" rel="tag">MySQL</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%88%86%E4%BA%AB/" rel="tag">分享</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/" rel="tag">单元测试</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%AD%A6%E4%B9%A0%E6%80%BB%E7%BB%93/" rel="tag">学习总结</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96/" rel="tag">自动化</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


  
    

  
</aside>
        
      </div>
      <a id="totop" href="#top"></a>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      <p>
        <a href="/blog/sitemap.xml">网站地图</a>
        <span> | </span><a href="/blog/atom.xml">订阅本站</a>
        <span> | </span><a href="/blog/about/">联系博主</a>
      </p>
      
        <p>
          <i class="fa fa-visitors"></i>
          <i id="busuanzi_container_site_uv"><i id="busuanzi_value_site_uv"></i></i>
          ，
          <i class="fa fa-views"></i>
          <i id="busuanzi_container_site_pv"><i id="busuanzi_value_site_pv"></i></i>
        </p>
      
      <p>
        <span>Copyright &copy; 2023 奉孝.</span>
        <span>Theme by <a href="https://github.com/chaooo/hexo-theme-BlueLake/" target="_blank">BlueLake.</a></span>
        <span>Powered by <a href="https://hexo.io/" target="_blank">Hexo.</a></span>
      </p>
    </div>
  </div>
</footer>

    </div>
  </div>
  
<script src="/blog/js/jquery-3.4.1.min.js"></script>


<script src="/blog/js/search.json.js"></script>


  
<script src="/blog/fancybox/jquery.fancybox.min.js"></script>




<script src="/blog/js/script.js"></script>






  
<script src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




  
    
<script src="/blog/localshare/js/social-share.js"></script>

    
<script src="/blog/localshare/js/qrcode.js"></script>

  
  



  

  

  

  

  

  

  

  
  





</body>
</html>